import {
  updateUserInfo,
  userInfo
} from '../../api/user'
import config from '../../config/env'
import log from '../../utils/log'


Page({
  data: {
    avatarUrl: config.DEFAULT_IMAGE_URL,
    theme: wx.getSystemInfoSync().theme,
    nickname: ''
  },
  onLoad() {
    wx.onThemeChange((result) => {
      this.setData({
        theme: result.theme
      })
    })
    const user = wx.getStorageSync('user')
    this.setData({
      avatarUrl: user.avatar || config.DEFAULT_IMAGE_URL,
      nickname: user.nickname
    })
  },
  onChooseAvatar(e) {
    // const {
    //   avatarUrl
    // } = e.detail
    // this.setData({
    //   avatarUrl,
    // })
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: 'compressed',
      success(res) {
        const tempFilePaths = res.tempFiles
        wx.showLoading()
        wx.uploadFile({
          url: `${config.API_URL}/file/sysFile/upload`,
          filePath: tempFilePaths[0].tempFilePath,
          name: 'file',
          header: {
            Authorization: `Bearer ${wx.getStorageSync('token')}`
          },
          success(res) {
            wx.hideLoading()
            const data = JSON.parse(res.data)
            if (data.code === 200) {
              that.setData({
                avatarUrl: data.data.url
              })
            } else {
              log.error(res)
            }
          },
          fail(err) {
            wx.hideLoading()
            log.error(err)
          }
        })
      }
    })
  },
  doSubmit() {
    // debugger
    if (!this.data.nickname) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'error'
      })
      return false
    }

    const params = {
      avatar: this.data.avatarUrl,
      nickname: this.data.nickname
    }
    updateUserInfo(params).then(() => {
      // 防止覆盖加载框
      userInfo().then(res => {
        wx.setStorageSync('user', res)
        wx.showToast({
          title: '操作成功',
        })
      })
    })
  }
})